import requests
import datetime
import time
import json
import os
import logging
import pandas as pd
import threading
from socket import *

# config读取
config = json.loads(open(r'checkConfig.json', encoding='utf-8').read())
# 消息推送
HOST = config["sendIP"]
PORT = config["sendPort"]
# 监控ID
monitor = config["monitor"]
# 启动时间
startTime = config["start"]
# 结束关闭时间
shutdown = config["end"]

ADDR = (HOST, PORT)
thisPath = os.getcwd()
tomcats = config['tomcat']

isDoStart = True
isDoEnd = True


# 创建一个logger
logger = logging.getLogger('listen')
logger.setLevel(logging.DEBUG)

# 创建一个handler，用于写入日志文件
fh = logging.FileHandler('see.log')
fh.setLevel(logging.DEBUG)

# 定义handler的输出格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)

# 给logger添加handler
logger.addHandler(fh)


# 启动tomcat
def startTomcat(path):
    os.chdir(path + "\\bin")
    os.system(".\\startup.bat")


# 启动Nginx
def startNginx(path, fileName):
    os.chdir(path)
    # os.path.exists(fileName)
    os.popen('start ' + fileName)


# 根据端口干掉
def kill_port(port):
    find_port = 'netstat -aon | findstr :%s | findstr LISTENING' % port
    result = os.popen(find_port)
    info = result.read().split('\n')
    data = []
    for line in info:
        if not line:
            continue
        temp = [str for str in line.split(" ") if str]
        data.append(temp)
    parser_cmd(data)


# 干掉他！！！
def parser_cmd(data):
    columns = ["type", "secret", "open", "status", "pid"]
    df = pd.DataFrame(data=data, columns=list(columns))
    for index in range(len(data)):
        pid = df.loc[index, 'pid']
        kill_pid(pid)


# 根据PID干掉
def kill_pid(pid):
    find_kill = 'taskkill -f -pid %s' % pid
    os.popen(find_kill)


# 停止Nginx
def stopNginx(path, fileName):
    os.chdir(path)
    os.popen(fileName + '  -s stop')


# 检查系统是否还存活 true 还存活， false 已经关闭
def checkWeb(checkUrl):
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
                          'Chrome/35.0.1916.153 Safari/537.36 SE 2.X MetaSr 1.0'}
        response = requests.get(url=checkUrl, timeout=2, headers=headers)  # 请求超时时间为10秒
        code = response.status_code  # http请求的返回状态，若为200则表示请求成功,返回的状态码是 int类型
        if code == 200:
            return True
        else:
            return False
    except:
        return False


def sendMSG(msg):
    try:
        tcpCliSock = socket(AF_INET, SOCK_STREAM)
        tcpCliSock.connect(ADDR)
        data = {"type": "forward", "monitor": monitor, "msg": msg}
        tcpCliSock.send(str(data).encode())
        tcpCliSock.close()
    except Exception as r:
        logger.error(str(r) + '--------sendMSG' + '\n' + msg)
        print('请求失败，继续请求')


def doTimerStart():
    global isDoStart
    #先获取当前时间
    now = time.localtime()
    hour = str(now.tm_hour) if now.tm_hour > 10 else '0'+str(now.tm_hour)
    minute = str(now.tm_min) if now.tm_min > 10 else '0'+str(now.tm_min)
    logger.debug('start---' + hour + ':' + minute)
    if (hour + ':' + minute) == startTime and isDoStart:
        isDoStart = False
        startAll()
    else:
        isDoStart = True


def doTimerStop():
    global isDoEnd
    # 先获取当前时间
    now = time.localtime()
    hour = str(now.tm_hour) if now.tm_hour > 10 else '0'+str(now.tm_hour)
    minute = str(now.tm_min) if now.tm_min > 10 else '0'+str(now.tm_min)
    logger.debug('stop---' + hour + ':' + minute)
    if (hour + ':' + minute) == shutdown and isDoEnd:
        isDoEnd = False
        stopAll()
    else:
        isDoEnd = True


# 关闭应用
def stopAll():
    sendMSG('开始关闭所有配置项')
    for item in tomcats:
        if item['type'] == 'tomcat':
            kill_port(item['port'])
        elif item['type'] == 'nginx':
            stopNginx(item['nginxPath'], item['nginxFile'])
    sendMSG('配置项全部关闭')


def startAll():
    sendMSG('开始启动所有配置项')
    for item in tomcats:
        if item['type'] == 'tomcat':
            startTomcat(item['tomcatPath'])
            sendMSG('启动' + item['name'] + '中')
            while True:
                if checkWeb(item["checkUrl"]):
                    sendMSG(item["name"] + "启动成功")
                    break
                else:
                    sendMSG('启动' + item['name'] + '中')
                    time.sleep(5)
        elif item['type'] == 'nginx':
            startNginx(item['nginxPath'], item['nginxFile'])
            time.sleep(5)
            if checkWeb(item['checkUrl']):
                sendMSG(item["name"] + "启动成功")
            else:
                sendMSG(item["name"] + "启动失败")
    sendMSG('配置项全部启动')


# 启动执行开始方法
def startTimer():
    try:
        do = threading.Thread(target=doTimerStart, )
        do.start()
        while do.is_alive():
            time.sleep(0.5)
    except Exception as r:
        logger.error(str(r))
    finally:
        threading.Timer(30, startTimer, ()).start()


# 关闭执行开始方法
def endTimer():
    try:
        do = threading.Thread(target=doTimerStop, )
        do.start()
        while do.is_alive():
            time.sleep(0.5)
    except Exception as r:
        logger.error(str(r))
    finally:
        threading.Timer(30, endTimer, ()).start()


def selfHeart():
    try:
        tcpCliSock = socket(AF_INET, SOCK_STREAM)
        tcpCliSock.connect(ADDR)
        data = {"type": "heart", "monitor": monitor}
        tcpCliSock.send(str(data).encode())
        tcpCliSock.close()
    except Exception as r:
        logger.error(str(r) + '--------selfHeart')
    finally:
        threading.Timer(60, selfHeart, ()).start()


threading.Thread(target=selfHeart, ).start()
startTimer()
endTimer()
sendMSG('项目定时重启 监控启动')